package cn.edu.gznu.wecampus.core.auth;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.edu.gznu.wecampus.core.common.entity.jpa.User;
import cn.edu.gznu.wecampus.core.common.repository.jpa.UserRepository;
import cn.edu.gznu.wecampus.core.service.PropertyService;
import cn.edu.gznu.wecampus.core.utils.JwtUtils;
import cn.edu.gznu.wecampus.core.web.RestResponse;
import cn.edu.gznu.wecampus.core.web.RestResponseElement;

@RestController
@RequestMapping("/api/form")
public class FormApi {
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private PropertyService propertyService;
	
	@RequestMapping("jwt")
	public RestResponse jwt(String username, String password) {
		SimpleHash simpleHash = new SimpleHash("sha-1", password);
		simpleHash.setIterations(1);
		String passwordHex = simpleHash.toHex();
		User user = userRepository.findByUsername(username);
		if(user == null || !StringUtils.equals(user.getPasswordHex(), passwordHex)) {
			throw new AuthenticationException(
				propertyService.getProperty("pointcircle.framework.message.auth.username-or-password-wrong")
			);
		}
		String jwtToken = JwtUtils.sign(username);
		RestResponseElement response = new RestResponseElement();
		AuthVo vo = new AuthVo();
		vo.setXgh(user.getUsername());
		vo.setName(user.getRealname());
		vo.setJwtToken(jwtToken);
		response.setElement(vo);
		return response;
	}
}
